<?php
/**
 * PHP Framework Core Cache class
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/
class Cache {

    /**
     * Keeps cached data items
     **/
    private $_data = array();

    /**
     * Gets a value indicating whether a cached item
     * corresponding to the given key exists
     **/
    public function exists($key) {

        return isset($this->_data[$key]);
    }

    /**
     * Gets a cached value corresponding to the given key
     **/
    public function get($key) {

        if (isset($this->_data[$key])) {

            return $this->_data[$key];
        }

        return null;
    }

    /**
     * Sets a cached value corresponding to the given key
     **/
    public function set($key, $value) {

        $this->_data[$key] = $value;
    }

    /**
     * Loads cached data from the current cache device
     **/
    public static function load() {
        return Cache::loadFromFile();
    }

    /**
     * Saves cached data to the current cache device
     **/
    public function save() {
        $this->saveToFile();
    }

    /**
     * Loads cached data from the session array
     * @return Cache
     **/
    private static function loadFromSession() {

        if (isset($_SESSION['Framework.Core.Caching.Cache'])) {
            return $_SESSION['Framework.Core.Caching.Cache'];
        }

        return new Cache();
    }

    /**
     * Saves cache instance to the session array
     **/
    private function saveToSession() {

        $_SESSION['Framework.Core.Caching.Cache'] = $this;
    }

    /**
     * Loads cached data from a file
     * @return Cache Resulting cache object
     **/
    private static function loadFromFile() {

        $strFileName = "Framework.Core.Caching.Cache.dmp";

        if (is_file($strFileName)) {

            $data = file_get_contents($strFileName);
            $Cache = unserialize($data);
            return $Cache;
        }

        return new Cache();
    }

    /**
     * Saves cache instance to a file
     **/
    private function saveToFile() {

        $strFileName = "Framework.Core.Caching.Cache.dmp";

        $data = serialize($this);
        file_put_contents($strFileName, $data);
    }
}
?>
